package com.sunday.pinxinghui.model.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.UploadUtils;

import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.CommonAdapter;
import com.sunday.pinxinghui.adapter.GradImageAdapter;
import com.sunday.pinxinghui.adapter.ViewHolder;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.Images;
import com.sunday.pinxinghui.entity.Order;
import com.sunday.pinxinghui.entity.OrderItem;
import com.sunday.pinxinghui.network.ApiClient;
import com.sunday.pinxinghui.widgets.MyRatingBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2017/8/20.
 */

public class MakeCommentActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;

    private Order order;
    private CommentAdapter adapter;
    private List<OrderItem> dataSet = new ArrayList<>();
    private List<ArrayList<String>> images = new ArrayList<>();
    private List<GradImageAdapter> adapters = new ArrayList<>();
    private List<Images> imagesList = new ArrayList<>();
    private List<String> contents = new ArrayList<>();
    private List<String> prductIds = new ArrayList<>();
    private long memberId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make_comment);
        ButterKnife.bind(this);
        order = (Order) getIntent().getSerializableExtra("order");
        memberId = BaseApplication.getInstance().getMember().getId();
        //memberId = Constants.TEST_MEMBERID;
        if (order != null && order.getItems() != null) {
            dataSet.addAll(order.getItems());
            int i = 0;
            for (OrderItem orderItem : order.getItems()) {
                contents.add("");
                prductIds.add(String.valueOf(orderItem.getProductId()));
                images.add(new ArrayList<String>());
                adapters.add(new GradImageAdapter(8, images.get(i), i));
                i++;
            }
            images.add(new ArrayList<String>());
            adapters.add(new GradImageAdapter(8, images.get(i), i));
        }
        titleView.setText("评价");
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new CommentAdapter(mContext, R.layout.item_comment, dataSet);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.horizontal_space_divider).build());
    }

    @OnClick(R.id.btn_submit)
    void comment() {
        if (getImagesList().size() != 0) {
            UpImgae();
        } else {
            Comment();
        }

    }

    private void UpImgae() {

        showLoadingDialog(0);

        Call<ResultDO<List<Images>>> call = ApiClient.getApiAdapter().saveImages(UploadUtils.getRequestBody(getImagesList()));
        call.enqueue(new Callback<ResultDO<List<Images>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Images>>> call, Response<ResultDO<List<Images>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    imagesList.addAll(response.body().getResult());
                    Comment();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Images>>> call, Throwable t) {

            }
        });

    }

    private void Comment() {

        Call<ResultDO> call = ApiClient.getApiAdapter().doComment(order.getOrderId(), memberId, StringUtils.listToString(prductIds), adapter.getScores2(), adapter.getScores1(), adapter.getContents(), getImgPath());
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "评价成功");
                    finish();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {

            }
        });

    }

    private int[] imagesNum;

    private List<String> getImagesList() {
        imagesNum = new int[images.size()];
        int i = 0;
        List<String> list = new ArrayList<>();
        for (List<String> image : images) {
            for (String imagePath : image) {
                list.add(imagePath);
            }
            imagesNum[i] = image.size();
            i++;
        }
        return list;
    }

    private String getImgPath() {

        List<List<String>> list = new ArrayList<>();

        int k = 0;
        for (int i = 0; i < imagesNum.length; i++) {
            List<String> list1 = new ArrayList<>();
            for (int j = 0; j < imagesNum[i]; j++) {
                list1.add(imagesList.get(k).getSaveUrl());
                k++;
            }
            list.add(list1);
        }

        String img = "";

        int l = 0;
        for (List<String> strings : list) {
            if (strings != null) {
                int ll = 0;
                for (String imagePath : strings) {
                    if (ll == 0) {
                        img = img + imagePath;
                    } else {
                        img = img + "#" + imagePath;
                    }

                    ll++;
                }
            }
            if (l < list.size() - 1) {
                img = img + ",";
            }
            l++;
        }
        return img;
    }


    class CommentAdapter extends CommonAdapter<OrderItem> {

        private SparseArray<MyRatingBar> myRatingBars1 = new SparseArray<>();
        private SparseArray<MyRatingBar> myRatingBars2 = new SparseArray<>();


        public CommentAdapter(Context context, int layoutId, List<OrderItem> datas) {
            super(context, layoutId, datas);
        }

        @Override
        public void convert(ViewHolder holder, OrderItem orderItem, final int position) {
            ImageView proImg = holder.getView(R.id.product_img);
            if (!TextUtils.isEmpty(orderItem.getProductImage())) {
                Glide.with(mContext)
                        .load(orderItem.getProductImage())
                        .error(R.mipmap.ic_default)
                        .placeholder(R.mipmap.ic_default)
                        .into(proImg);
            }
            ((TextView) holder.getView(R.id.product_name)).setText(orderItem.getProductName());
            MyRatingBar myRatingBar1 = holder.getView(R.id.service_rating_bar);
            MyRatingBar myRatingBar2 = holder.getView(R.id.send_rating_bar);
            myRatingBar1.setRating(5, R.drawable.rating_bar, true, 30);
            myRatingBar2.setRating(5, R.drawable.rating_bar, true, 30);
            myRatingBars1.put(position, myRatingBar1);
            myRatingBars2.put(position, myRatingBar2);
            NoScrollGridView gridView = holder.getView(R.id.grid_view);
            gridView.setAdapter(adapters.get(position));
            EditText editText = holder.getView(R.id.edit_text);
            editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    contents.set(position, s.toString());
                }
            });
            adapters.get(position).setOnClickListener(clickListener);
        }

        private String getContents() {

            String content = "";
            int i = 0;
            for (String con : contents) {

                if (!TextUtils.isEmpty(con)) {
                    content = content + con;
                }
                if (i < contents.size() - 1) {
                    content = content + "@@@";
                }
                i++;
            }
            return content;
        }

        private String getScores1() {

            String scores = "";
//            for (MyRatingBar myRatingBar : ratingBars1) {
//                scores = scores + String.valueOf(myRatingBar.getRating()) + ",";
//            }
            for (int i = 0; i < myRatingBars1.size(); i++) {
                scores = scores + String.valueOf(myRatingBars1.get(i).getRating()) + ",";
            }
            scores = scores.substring(0, scores.length() - 1);
//            if (ratingBars1.size() != dataSet.size()) {
//                for (int k = 0; k < dataSet.size() - ratingBars1.size(); k++) {
//                    scores = scores + 5;
//                    if (k < dataSet.size() - ratingBars1.size() - 1) {
//                        scores = scores + ",";
//                    }
//                }
//            }
            return scores;
        }

        private String getScores2() {
            String scores = "";
//            for (MyRatingBar myRatingBar : ratingBars2) {
//                scores = scores + String.valueOf(myRatingBar.getRating()) + ",";
//            }
            for (int i = 0; i < myRatingBars2.size(); i++) {
                scores = scores + String.valueOf(myRatingBars2.get(i).getRating()) + ",";
            }
            scores = scores.substring(0, scores.length() - 1);
//            if (ratingBars2.size() != dataSet.size()) {
//                for (int k = 0; k < dataSet.size() - ratingBars2.size(); k++) {
//                    scores = scores + 5;
//                    if (k < dataSet.size() - ratingBars2.size() - 1) {
//                        scores = scores + ",";
//                    }
//                }
//        }
            return scores;
        }

    }


    private int parentPosition;

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            parentPosition = (int) v.getTag(v.getId());

            switch (v.getId()) {
                case R.id.photo_add:
                    if (images.get(parentPosition).size() == (int) v.getTag()) {
                        toImage(3 - images.get(parentPosition).size());
                    } else {
//                        intent = new Intent(mContext, ShowBigImage.class);
//                        intent.putStringArrayListExtra("data", images.get(parentPosition));
//                        intent.putExtra("index", (int) v.getTag());
//                        startActivity(intent);
                    }
                    break;
                case R.id.photo_delete:
                    images.get(parentPosition).remove((int) v.getTag());
                    adapter.notifyDataSetChanged();
                    break;
            }

        }
    };

    public void toImage(int max) {
        intent = new Intent(mContext, MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, max);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        startActivityForResult(intent, 1111);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1111:
                    ArrayList<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    for (String path : mSelectPath) {
                        images.get(parentPosition).add(ImageUtils.getCompressImagePath(path));
                    }
                    adapter.notifyDataSetChanged();
                    return;

            }
        }
    }


}






